import logging

from django.http import HttpRequest

from WebSite.models.AppModel import TUser
from WebSite.views.exceptions import AppException
from WebSite.views.misc import strtomd5

logger = logging.getLogger("system")


class Auth(object):
	SESSION_KEY_USER_ID = "userId"
	SESSION_KEY_USER_NAME = "userName"

	@staticmethod
	def Is_Authenticated(request):
		"""
		检查session， 
		:param request: 请求
		:return: 是否认证成功
		"""
		assert isinstance(request, HttpRequest)
		uid = request.session.get(Auth.SESSION_KEY_USER_ID, None)
		if uid is not None:
			return True
		return False

	@staticmethod
	def userId(request):
		assert isinstance(request, HttpRequest)
		return request.session.get(Auth.SESSION_KEY_USER_ID, None)

	@staticmethod
	def login(request, user):
		"""
		登陆，保存session信息
		:param request:
		:param user:
		"""
		assert isinstance(request, HttpRequest)
		request.session[Auth.SESSION_KEY_USER_ID] = user.user_id
		request.session[Auth.SESSION_KEY_USER_NAME] = user.user_name

	@staticmethod
	def logout(request):
		assert isinstance(request, HttpRequest)
		request.session[Auth.SESSION_KEY_USER_ID] = None
		request.session[Auth.SESSION_KEY_USER_NAME] = None

	@staticmethod
	def relogin(request):
		"""
		刷新会话
		:param request:
		"""
		assert isinstance(request, HttpRequest)
		uid = request.session.get(Auth.SESSION_KEY_USER_ID, None)
		request.session[Auth.SESSION_KEY_USER_ID] = uid

	@staticmethod
	def authenticate(username, password):
		"""
		登陆校验，判断是否是系统用户
		:param username:
		:param password:
		:return: user
		"""
		try:
			user = TUser.login(login_name=username, passwd=strtomd5(password))
			if user is None:
				raise TUser.DoesNotExist
			else:
				return user

		except TUser.DoesNotExist:
			raise AppException(username + ' 尝试登录，用户名不存在或密码不正确，或者密码已经过期')
